<?php
/**
 * 插件在线更新功能类
 *
 * @package DeepSeekAISummarizer
 * @since 3.8.0
 */

// 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

if (!class_exists('DeepSeekAI_Updater')) {

class DeepSeekAI_Updater {

    private $current_version;
    private $plugin_slug;
    private $plugin_basename;
    private $api_url;

    /**
     * 构造函数
     * @param string $current_version 当前插件版本
     * @param string $plugin_file 主插件文件路径
     */
    public function __construct($current_version, $plugin_file) {
        $this->current_version = $current_version;
        $this->plugin_basename = plugin_basename($plugin_file);
        $this->plugin_slug = dirname($this->plugin_basename);
        
        // 【重要】请在此处填写真实的 update-manifest.json 文件地址
        $this->api_url = 'https://wpaiupload.aiqji.com/update-manifest.json';

        // 挂载到WordPress更新检查的钩子
        add_filter('pre_set_site_transient_update_plugins', array($this, 'check_for_update'));
        
        // 挂载到插件信息弹窗的钩子
        add_filter('plugins_api', array($this, 'plugin_api_info'), 10, 3);
    }

    /**
     * 检查是否有新版本
     * @param object $transient WordPress插件更新的瞬态数据
     * @return object
     */
    public function check_for_update($transient) {
        if (empty($transient->checked)) {
            return $transient;
        }

        $remote_info = $this->get_remote_info();

        if ($remote_info && version_compare($this->current_version, $remote_info->version, '<')) {
            $plugin_info = new stdClass();
            $plugin_info->slug = $this->plugin_slug;
            $plugin_info->new_version = $remote_info->version;
            $plugin_info->url = $remote_info->homepage;
            $plugin_info->package = $remote_info->download_url;
            $plugin_info->tested = $remote_info->tested;
            $plugin_info->icons = (array) $remote_info->icons;
            $plugin_info->banners = (array) $remote_info->banners;

            $transient->response[$this->plugin_basename] = $plugin_info;
        }

        return $transient;
    }

    /**
     * 在插件信息弹窗中显示远程信息（如更新日志）
     * @param bool|object $res
     * @param string $action
     * @param object $args
     * @return bool|object
     */
    public function plugin_api_info($res, $action, $args) {
        if ($action !== 'plugin_information' || !isset($args->slug) || $args->slug !== $this->plugin_slug) {
            return $res;
        }

        $remote_info = $this->get_remote_info();
        if ($remote_info) {
            $res = new stdClass();
            $res->name = $remote_info->name;
            $res->slug = $this->plugin_slug;
            $res->version = $remote_info->version;
            $res->author = $remote_info->author;
            $res->author_profile = $remote_info->author_profile;
            $res->homepage = $remote_info->homepage;
            $res->download_link = $remote_info->download_url;
            $res->requires = $remote_info->requires;
            $res->tested = $remote_info->tested;
            $res->last_updated = $remote_info->last_updated;
            $res->sections = (array) $remote_info->sections;
            $res->banners = (array) $remote_info->banners;
            $res->icons = (array) $remote_info->icons;

            return $res;
        }

        return false;
    }

    /**
     * 从远程URL获取插件信息
     * @return object|null
     */
    private function get_remote_info() {
        $response = wp_remote_get($this->api_url, array(
            'timeout' => 10,
            'headers' => array(
                'Accept' => 'application/json'
            )
        ));

        if (is_wp_error($response) || 200 !== wp_remote_retrieve_response_code($response)) {
            return null;
        }

        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body);

        if (is_object($data)) {
            return $data;
        }

        return null;
    }
    
    /**
     * 强制检查更新并返回结果
     * @return array
     */
    public function force_check_update() {
        $remote_info = $this->get_remote_info();

        if (!$remote_info) {
            return array(
                'status' => 'error',
                'message' => '无法连接到更新服务器或解析更新信息失败。'
            );
        }

        if (version_compare($this->current_version, $remote_info->version, '<')) {
            // 发现新版本，清除缓存以确保更新提示能在插件列表页显示
            delete_site_transient('update_plugins');

            return array(
                'status'      => 'update_available',
                'message'     => '发现新版本！',
                'new_version' => $remote_info->version,
                'changelog'   => $remote_info->sections->changelog ?? '暂无更新日志。'
            );
        } else {
            return array(
                'status'  => 'no_update',
                'message' => '您当前使用的已是最新版本。'
            );
        }
    }
}

} 